package com.alennus.blog.controller;

import com.alennus.blog.dto.MediaDto;
import com.alennus.blog.response.WebApiResponse;
import com.google.common.io.Files;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * Created by pactera on 2018/5/23.
 */
@RestController
@RequestMapping("/media")
public class MediaController {
    public static final String IMAGE_ROOT = "/images";



    @Value("${media.server.root}")
    private String root;
    @Value("${media.server.url}")
    private String mediaServerUrl;


    @PostMapping("/image")
    public WebApiResponse<MediaDto> handleImageUpload(@RequestParam("file") MultipartFile file) {

        if (!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();

//            if(!FileUploadValidator.validate(FileUploadValidator.IMAGE_PATTERN,originalFilename)){
//                throw new BusinessException(BusinessExceptionCode.INVALID_UPLOAD_FILE_ERROR);
//            }
            String fileExtension = Files.getFileExtension(originalFilename);
            String imagePath = root + IMAGE_ROOT;

            String newFileName = System.currentTimeMillis() + "." + fileExtension;
            String newPath = new StringBuilder(imagePath).append(File.separator).append(newFileName).toString();
            final File newFile = new File(newPath);
            try {
                Files.createParentDirs(newFile);
                Files.write(file.getBytes(), newFile);
            } catch (IOException e) {
            }

            MediaDto media = new MediaDto();
            media.setOriginalName(originalFilename);
            media.setNewName(newFileName);
            media.setFullName(IMAGE_ROOT + "/" + newFileName);
            media.setUrl(mediaServerUrl+"/"+IMAGE_ROOT +"/"+ newFileName);
            return WebApiResponse.success(media);
        }

        return WebApiResponse.error("file is empty");
    }
}
